package zhttp

import (
    "context"
    "encoding/json"
    "fmt"
    "net/http"

    "gitee.com/shijingzhao/z-frame/zlog"
)

const (
    // ContentType means Content-Type.
    ContentType = "Content-Type"
    // ApplicationJson means application/json.
    ApplicationJson = "application/json"
)

type body struct {
    Code int         `json:"code"`
    Msg  string      `json:"msg"`
    Data interface{} `json:"data,omitempty"`
}

func OutputJson(w http.ResponseWriter, code int, msg string, data interface{}) {
    w.Header().Set(ContentType, ApplicationJson)

    j, err := json.Marshal(body{
        Code: code,
        Msg:  msg,
        Data: data,
    })
    if err != nil {
        zlog.NewSystemLogger(context.TODO()).Error(
            "http.ResponseWriterErr",
            zlog.String("msg", "json.Marshal"),
            zlog.String("err", err.Error()),
            zlog.Struct("w", w),
            zlog.Int("code", code),
            zlog.String("msg", msg),
            zlog.Interface("data", data),
        )
        return
    }

    _, err = fmt.Fprintln(w, string(j))
    if err != nil {
        zlog.NewSystemLogger(context.TODO()).Error(
            "http.ResponseWriterErr",
            zlog.String("msg", "fmt.Fprintln"),
            zlog.String("err", err.Error()),
            zlog.Struct("w", w),
            zlog.String("j", string(j)),
        )
        return
    }
}
